using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks;
using Microsoft.Build.Framework;
using System.Diagnostics;
using System.IO;

namespace BizTalk.BuildGenerator.Tasks.VisualStudio
{
    /// <summary>
    /// Executes MsTest to run tests for your BizTalk solution
    /// </summary>
    public class MsTestExecutor : Task
    {
        private string _MsTestPath;
        private string _TestRunConfigPath;
        private ITaskItem[] _TestAssemblyPaths;

        /// <summary>
        /// Ctor
        /// </summary>
        public MsTestExecutor()
        {
            string basePath = Environment.GetEnvironmentVariable("VS90COMNTOOLS");
            this._MsTestPath = string.Format("\"{0}..\\IDE\\mstest.exe\" ", basePath);
            Trace.WriteLine("MsTest Path: " + this._MsTestPath);
        }
        /// <summary>
        /// The paths to the assemblies to test
        /// </summary>
        public ITaskItem[] TestAssemblyPaths
        {
            get { return _TestAssemblyPaths; }
            set { _TestAssemblyPaths = value; }
        } 
        /// <summary>
        /// The path to the test run config
        /// </summary>
        public string TestRunConfigPath
        {
            get { return _TestRunConfigPath; }
            set { _TestRunConfigPath = value; }
        }
        /// <summary>
        /// Optionally specify a path for MsTest
        /// </summary>
        public string MsTestPath
        {
            get { return _MsTestPath; }
            set { _MsTestPath = value; }
        }
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {            
            StringBuilder sb = new StringBuilder();
            sb.Append(this._MsTestPath);

            //Add test containers
            if (this._TestAssemblyPaths != null)
            {
                foreach (ITaskItem taskItem in this._TestAssemblyPaths)
                {
                    string assemblyPath = taskItem.ItemSpec;                    
                    sb.AppendFormat("/testcontainer:\"{0}\" ", assemblyPath);
                }
            }
            
            //Add test run config
            if (!string.IsNullOrEmpty(this._TestRunConfigPath))
                sb.AppendFormat("/runconfig:\"{0}\"", this._TestRunConfigPath);

            Trace.WriteLine("Executing command: " + sb.ToString());
            Microsoft.Build.Tasks.Exec exec = new Microsoft.Build.Tasks.Exec();
            exec.BuildEngine = this.BuildEngine;

            exec.Command = sb.ToString();
            return exec.Execute();
        }
    }
}
